﻿#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import json
import urllib2
import recipe

def make_host_dict(filename):
  d = {}
  for line in open(filename):
    line = line.strip()
    last_slash = line.rfind('/')
    d["img" + line[last_slash:]] = line
    d["/img" + line[last_slash:]] = line
  return d

def use_host_images():
  DATA = "data/gotovim_doma.json"
  NEW_DATA = "data/gotovim_doma_hosted.json"
  HOST_IMAGES_FILE = "data/gotovim_doma_host_images.txt"

  host_dict = make_host_dict(HOST_IMAGES_FILE)
  outfile = open(NEW_DATA, 'w')

  for line in open(os.path.join(os.getcwd(), DATA)):
    r = recipe.Recipe.from_json(json.loads(line))
    
    if r.main_photo in host_dict:
      r.main_photo = host_dict[r.main_photo]
    else:
      r.main_photo = ""

    outfile.write(r.as_json() + "\n")

use_host_images()
